﻿using Albatross.SSRSViewer.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Albatross.SSRSViewer.Views {
	/// <summary>
	/// Interaction logic for ReportViewerView.xaml
	/// </summary>
	public partial class ReportViewerView : UserControl {
		public ReportViewerView() {
			InitializeComponent();
			DataContextChanged += ReportViewerView_DataContextChanged;
		}

		void ReportViewerView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
			if (e.NewValue != null) {
				InitReportViewer((ReportViewerViewModel)e.NewValue);
			}
		}

		void TreeViewItem_DoubleClick(object sender, RoutedEventArgs e) {
			TreeViewItem item = e.Source as TreeViewItem;
			if (item != null && item.IsSelected) {
				ReportItemViewModel vm = Tree.SelectedItem as ReportItemViewModel;
				if (vm != null && (vm.Type == ReportItemViewModel.Report_Type || vm.Type == ReportItemViewModel.LinkedReport_Type)) {
					RunReport(vm, null);
					e.Handled = true;
				}
			}
		}

		void InitReportViewer(ReportViewerViewModel vm) {
			ReportViewer.ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultNetworkCredentials;
			ReportViewer.ServerReport.ReportServerUrl = vm.ReportServerUri;
			ReportViewer.ServerReport.Timeout = System.Threading.Timeout.Infinite;
		}

		void RunReport(ReportItemViewModel vm, IDictionary<string, string> parameters) {
			ReportViewerViewModel reportViewersViewModel = DataContext as ReportViewerViewModel;
			if (vm.Type == ReportItemViewModel.Report_Type || vm.Type == ReportItemViewModel.LinkedReport_Type) {
				reportViewersViewModel.Title = string.Format("{0}@{1}", vm.Name, reportViewersViewModel.Server);
				ReportViewer.ServerReport.ReportPath = vm.Path;
				ReportViewer.RefreshReport();
			}
		}

		private void ExpandSelected_Click(object sender, RoutedEventArgs e) {
			if (Tree.SelectedItem != null) {
				((ReportItemViewModel)Tree.SelectedItem).ExpandCollapse(true, true);
			}
		}

		private void CollapseSelected_Click(object sender, RoutedEventArgs e) {
			if (Tree.SelectedItem != null) {
				((ReportItemViewModel)Tree.SelectedItem).ExpandCollapse(false, true);
			}
		}

		private void AlbatrossDockPanel_LeftDragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e) {
			WinFormHost.Visibility = System.Windows.Visibility.Collapsed;
		}

		private void AlbatrossDockPanel_LeftDragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) {
			WinFormHost.Visibility = System.Windows.Visibility.Visible;
		}
	}
}
